<!DOCTYPE>
<html>
<head>
    <meta charset="utf-8"/>
    <title>聊天室DEMO</title>
    <script src="../js/jquery-1.12.3.min.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css"/>
    <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <style>
        body {
            margin-top: 5px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-3">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title">当前登录用户</h3>
                </div>
                <div class="panel-body">
                    <div class="list-group">
                        <a href="#" class="list-group-item">你好，<span id="user"></span></a>
                    </div>
                </div>
            </div>
            <div class="panel panel-primary" id="online">
                <div class="panel-heading">
                    <h3 class="panel-title">当前在线的其他用户</h3>
                </div>
                <div class="panel-body">
                    <div class="list-group" id="users">
                    </div>
                </div>
            </div>
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title">广播消息</h3>
                </div>
                <div class="panel-body">
                    <input type="text" class="form-control" id="msg"/><br>
                    <button id="broadcast" type="button" class="btn btn-primary">发送</button>
                </div>
            </div>
            <!--			文件传输	-->
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title">文件发送</h3>
                </div>
                <div class="panel-body">
                    <a href="javascript:;" class="file">选择文件
                        <input type="file" name="" onchange="fileOnchange()" id="fileId"> <span id="filename"
                                                                                                style="color: red"></span>
                    </a>
                </div>
            </div>
        </div>
        <div class="col-md-9">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title" id="talktitle"></h3>
                </div>
                <div class="panel-body">
                    <div class="well" id="log-container" style="height:400px;overflow-y:scroll">

                    </div>
                    <input type="text" id="myinfo" class="form-control col-md-12"/> <br>
                    <button id="send" type="button" class="btn btn-primary">发送</button>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var fileObject;//文件对象
    var uploadFlag = true;//文件上传的标识
    var paragraph = 10485760;//文件分块上传大小
    var startSize, endSize = 0;//文件的起始大小和文件的结束大小
    var i = 0;//第几部分文件

    Date.prototype.format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1,                 //月份
            "d+": this.getDate(),                    //日
            "h+": this.getHours(),                   //小时
            "m+": this.getMinutes(),                 //分
            "s+": this.getSeconds(),                 //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds()             //毫秒
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    }


    $(document).ready(function () {
        var user;
        // 指定websocket路径
        var websocket;
        $.get("/im/user/currentuser", function (data) {
            user = data.data;
            $("#user").html(user);

            if ('WebSocket' in window) {
                // websocket = new WebSocket("ws://139.224.215.119:8080/im/ws/" + user);
                websocket = new WebSocket("ws://localhost:8080/im/ws/" + user);
            }
            websocket.onmessage = function (event) {
                console.log(event.data)

                if (uploadFlag === false) {
                    //文件对象赋值
                    let filedata = fileObject;
                    //开始上传文件 收到next开始上传下一分片
                    if (event.data === 'next') {
                        //判断结束大小是否大于文件大小
                        if (endSize < filedata.size) {
                            $("#log-container").append("file_size:" + filedata.size+ '<br/>');
                            startSize = endSize;
                            endSize += paragraph;
                            $("#log-container").append("start_size:" + startSize+'<br/>');
                            $("#log-container").append("end_size:" + endSize+'<br/>');
                            $("#log-container").append("slice :"+ (++i) +'<br/>');
                            var blob = filedata.slice(startSize, endSize);
                            var reader = new FileReader();
                            reader.readAsArrayBuffer(blob);
                            reader.onload = function loaded(evt) {
                                var ArrayBuffer = evt.target.result;
                                $("#log-container").append("发送文件第" + i + "部分"+'<br/><br/>');
                                let fileObjJson={
                                    chatType:"NORMAL",
                                    msgType: "FILE",
                                    content:{
                                        index:i
                                    }
                                };
                                websocket.send(JSON.stringify(fileObjJson));
                                websocket.binaryType = 'arraybuffer';
                                websocket.send(ArrayBuffer);
                            }
                        } else {
                            $("#log-container").append("end_size :" + endSize+'<br/>');
                            $("#log-container").append("file_size:" + filedata.size+'<br/>');
                            startSize = endSize = 0;
                            i = 0;
                            $("#log-container").append("发送" + filedata.name + "完毕"+'<br/>');
                            let socketmess = {
                                chatType:"NORMAL",
                                msgType: "FILE",
                                content:{
                                    index:-1
                                }
                            };
                            let fileName = fileObject.name;
                            let suffix = fileName.substring(fileName.lastIndexOf("."));
                            if (suffix === ".png" || suffix === ".img" || suffix === ".jpg"){
                                socketmess.msgType = "PIC"
                            }else {
                                socketmess.msgType = "FILE"
                            }
                            websocket.send(JSON.stringify(socketmess));//告诉socket文件传输完毕，清空计数器
                        }
                    } else if (event.data === 'file_check_error'){
                        //此处获取
                        $("#log-container").append('<span style="color: red">文件传输失败,请检查您的网络情况</span><br/>');
                        fileObject = null;
                        uploadFlag = true;
                    } else if (event.data === 'file_upload_success'){
                        //此处获取
                        $("#log-container").append('<span style="color: green">文件传输成功</span><br/>');
                        fileObject = null;
                        uploadFlag = true;
                    }
                }else {
                    var data = JSON.parse(event.data);
                    if (data.chatType === "UP") {//上线消息
                        if (data.content != user) {
                            $("#users").append('<a href="#" onclick="talk(this)" class="list-group-item">' + data.content + '</a>');
                            alert(data.content + "上线了");
                        }
                    } else if (data.chatType === "DOWN") {//下线消息
                        if (data.content != user) {
                            $("#users > a").remove(":contains('" + data.content + "')");
                            alert(data.content + "下线了");
                        }
                    } else {
                        // 普通消息、广播消息
                        if (data.chatType === "NORMAL"){
                            // 文本消息、文件消息
                            if (data.msgType === "TEXT"){
                                let from = `来自${data.from}的消息`
                                $("#log-container").append("<div class='bg-info'><label class='text-danger'>" + from + "&nbsp;" + data.time + "</label><div class='text-success'>" + data.content + "</div></div><br>");
                            }else if (data.msgType === "FILE"){
                                let from = `来自${data.from}的文件消息`
                                let res = JSON.parse(data.content)
                                $("#log-container").append("<div class='bg-info'><label class='text-danger'>" + from + "&nbsp;" + data.time + "</label><div class='text-success'><a href='"+ res.url +"'>" + res.file + "</a></div></div><br>");
                            }else if (data.msgType === "PIC"){
                                let from = `来自${data.from}的图片消息`
                                let res = JSON.parse(data.content)
                                $("#log-container").append("<div class='bg-info'><label class='text-danger'>" + from + "&nbsp;" + data.time + "</label><div class='text-success'><img src='"+ res.url +"' title='"+ res.img +"' /></div></div><br>");
                            }
                        }else {
                            let from = `来自${data.from}的广播消息`
                            // 接收服务端的实时消息并添加到HTML页面中
                            $("#log-container").append("<div class='bg-info'><label class='text-danger'>" + from + "&nbsp;" + data.time + "</label><div class='text-success'>" + data.content + "</div></div><br>");
                        }
                        // 滚动条滚动到最低部
                        scrollToBottom();
                    }
                }
            };

            $.post("/im/user/onlineusers", function ({data}) {
                for (var i = 0; i < data.length; i++) {
                    if (data[i] != user) {
                        $("#users").append('<a href="#" onclick="talk(this)" class="list-group-item">' + data[i] + '</a>');
                    }
                }
            });

        });


        $("#broadcast").click(function () {
            var data = {};
            data["from"] = user;
            data["to"] = "*";
            data["chatType"] = "FANOUT";
            data["content"] = $("#msg").val();
            $("#msg").val("");
            websocket.send(JSON.stringify(data));
        });

        $("#send").click(function () {
            if ($("body").data("to") == undefined) {
                alert("请选择聊天对象");
                return false;
            }
            if (fileObject != null){
				uploadFileFun(websocket,user);
			}else {
                var data = {};
                data["from"] = user;
                data["to"] = $("body").data("to");
                data["chatType"] = "NORMAL";
                data["msgType"] = "TEXT";
                data["content"] = $("#myinfo").val();
                websocket.send(JSON.stringify(data));
                $("#log-container").append("<div class='bg-success'><label class='text-info'>我&nbsp;" + new Date().format("yyyy-MM-dd hh:mm:ss") + "</label><div class='text-info'>" + $("#myinfo").val() + "</div></div><br>");
                scrollToBottom();
                $("#myinfo").val("");
            }
        });

    });

    function talk(a) {
        $("#talktitle").text("与" + a.innerHTML + "的聊天");
        $("body").data("to", a.innerHTML);
    }

    function scrollToBottom() {
        var div = document.getElementById('log-container');
        div.scrollTop = div.scrollHeight;
    }

    //监听file域对象的变化，然后用于回显文件名
    function fileOnchange() {
        //从file域对象获取文件对象
        let files = $("#fileId")[0].files;
        //存储文件对象
        fileObject = files[0];
        //回显文件名
        $("#filename").html(fileObject.name);
    }

	//文件上传核心方法
	function uploadFileFun(socket,user) {
		//切换保存标识的状态
		uploadFlag = false;
		//先向后台传输文件名
		let fileName = fileObject.name;
		//后台只接收字符串类型，我们定义一个字符串的json对象给后台解析
        let fileJson =  {
            chatType:"NORMAL",
            msgType: "FILE",
            content:{
                index:0,
                originName: fileName,
                size:fileObject.size,
                chunk:paragraph,
                type:1
            },
            from:user,
            to:$("body").data("to")
        };

		//后台接收到文件名以后会正式开始传输文件
		socket.send(JSON.stringify(fileJson));
	}
</script>
<style>
    .file {
        position: relative;
        display: inline-block;
        background: #D0EEFF;
        border: 1px solid #99D3F5;
        border-radius: 4px;
        padding: 4px 12px;
        overflow: hidden;
        color: #1E88C7;
        text-decoration: none;
        text-indent: 0;
        line-height: 20px;
    }

    .file input {
        position: absolute;
        font-size: 100px;
        right: 0;
        top: 0;
        opacity: 0;
    }

    .file:hover {
        background: #AADFFD;
        border-color: #78C3F3;
        color: #004974;
        text-decoration: none;
    }
</style>
</body>
</html>
